package dao;

import java.util.Date;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import entity.Lieu;
import entity.Trajet;

@Stateless
@Local
public class TrajetDaoJpa implements TrajetDao {

	private EntityManager entityManager;

	@PersistenceContext(unitName = "MyPersistentUnit")
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Trajet> getAllTrajets() {
		Query query = entityManager.createQuery("select t from Trajet as t");
		List<Trajet> listeTrajet = query.getResultList();
		return listeTrajet;
	}

	@Override
	public Trajet getTrajetById(long id) {
		Trajet t = entityManager.find(Trajet.class, id);
		return t;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Trajet> getAllTrajetsDepuis(String lieuDepart) {
		Query query = entityManager
				.createQuery("SELECT t FROM Trajet AS t WHERE t.lieuDepart = ?1");
		query.setParameter(1, lieuDepart);
		List<Trajet> listeTrajet = query.getResultList();
		return listeTrajet;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Trajet> getTrajets(String lieuDepart, String lieuArrivee,
			Date allee, Date retour) {
		Query query = entityManager.createQuery("SELECT t FROM Trajet AS t "
				+ "WHERE t.lieuDepart = ?1" + " AND t.lieuArrivee = ?2");
		query.setParameter(1, new Lieu(lieuDepart));
		query.setParameter(2, new Lieu(lieuArrivee));
		List<Trajet> listeTrajet = query.getResultList();
		return listeTrajet;
	}

}
